package com.innovation.ic.cyz.base.service.cyz.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.cyz.base.mapper.cyz.*;
import com.innovation.ic.cyz.base.model.cyz.*;
import com.innovation.ic.cyz.base.pojo.enums.*;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.UserInfo;
import com.innovation.ic.cyz.base.pojo.constant.Constants;
import com.innovation.ic.cyz.base.pojo.constant.repairOrder.RepairOrderConstant;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order.*;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order_file.RepairOrderFileRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order_record.RepairOrderRecordRespPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.repair_order_type_head.RepairOrderTypeHeadInfoPojo;
import com.innovation.ic.cyz.base.service.cyz.RepairOrderService;
import com.innovation.ic.cyz.base.vo.cyz.RabbitMq.HqToCyzRepairOrderAddVo;
import com.innovation.ic.cyz.base.vo.cyz.RabbitMq.HqToCyzRepairOrderReplyVo;
import com.innovation.ic.cyz.base.vo.cyz.repairOrder.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;

/**
 * @desc   工单接口具体实现类
 * @author linuo
 * @time   2022年9月14日09:44:17
 */
@Service
@Transactional
public class RepairOrderServiceImpl extends ServiceImpl<RepairOrderMapper, RepairOrder> implements RepairOrderService {
    private static final Logger log = LoggerFactory.getLogger(RepairOrderServiceImpl.class);

    private Long firstTypeId = null;

    @Resource
    private ServiceHelper serviceHelper;

    @Resource
    private RepairOrderMapper repairOrderMapper;

    @Resource
    private RepairOrderFileMapper repairOrderFileMapper;

    @Resource
    private RepairOrderRecordMapper repairOrderRecordMapper;

    @Resource
    private RepairOrderTypeMapper repairOrderTypeMapper;

    @Resource
    private RepairOrderTypeHeadMapper repairOrderTypeHeadMapper;

    /**
     * 查询我的工单列表
     * @param userId 登录用户id
     * @return 返回我的工单列表数据
     */
    @Override
    public ServiceResult<RepairOrderWebListRespPojo> queryMyRepairOrder(Integer pageNo, Integer pageSize, String userId) {
        RepairOrderWebListRespPojo repairOrderWebListRespPojo = new RepairOrderWebListRespPojo();

        List<RepairOrderWebListPojo> result = repairOrderMapper.queryMyRepairOrder(pageNo, pageSize, userId);
        if(result != null && result.size() > 0){
            // 处理优先级数据
            for(RepairOrderWebListPojo repairOrderWebListPojo : result){
                repairOrderWebListPojo.setPriorityName(RepairOrderPriorityEnum.getDesc(Integer.valueOf(repairOrderWebListPojo.getPriorityName())));
            }
        }

        // 查询我的工单总数量
        Long count = repairOrderMapper.queryMyRepairOrderCount(userId);

        repairOrderWebListRespPojo.setCount(count);
        repairOrderWebListRespPojo.setData(result);

        ServiceResult<RepairOrderWebListRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(repairOrderWebListRespPojo);
        return serviceResult;
    }

    /**
     * 工单列表查询
     * @param repairOrderQueryListVo 工单列表查询的vo类
     * @return 返回工单查询结果
     */
    @Override
    public ServiceResult<RepairOrderAdminListRespPojo> queryRepairOrderList(RepairOrderQueryListVo repairOrderQueryListVo) {
        RepairOrderAdminListRespPojo result = new RepairOrderAdminListRespPojo();

        // 根据参数查询工单列表
        Map<String, Object> map = new HashMap<>();
        map.put(RepairOrderConstant.FIRST_TYPE_ID_FIELD, repairOrderQueryListVo.getFirstTypeId());
        map.put(Constants.ID, repairOrderQueryListVo.getId());
        map.put(RepairOrderConstant.PRIORITY_FIELD, repairOrderQueryListVo.getPriority());
        map.put(RepairOrderConstant.HEAD_USER_FIELD, repairOrderQueryListVo.getHeadUser());
        map.put(RepairOrderConstant.DEAL_USER_FIELD, repairOrderQueryListVo.getDealUser());
        map.put(Constants.PAGE_NO, repairOrderQueryListVo.getPageNo());
        map.put(Constants.PAGE_SIZE, repairOrderQueryListVo.getPageSize());

        // 创建日期
        String createDate = repairOrderQueryListVo.getCreateDate();
        if(!Strings.isNullOrEmpty(createDate)){
            map.put(Constants.START_TIME, createDate + " 00:00:00");
            map.put(Constants.END_TIME, createDate + " 23:59:59");
        }

        List<RepairOrderAdminListPojo> list = repairOrderMapper.selectRepairOrderListByParam(map);

        if(list != null && list.size() > 0){
            for(RepairOrderAdminListPojo repairOrderAdminListPojo : list){
                // 处理优先级
                String priority = repairOrderAdminListPojo.getPriority();
                if(!Strings.isNullOrEmpty(priority)){
                    repairOrderAdminListPojo.setPriority(RepairOrderPriorityEnum.getDesc(Integer.valueOf(priority)));
                }

                // 处理状态
                String status = repairOrderAdminListPojo.getStatus();
                if(!Strings.isNullOrEmpty(status)){
                    if(status.equals(RepairOrderStatusEnum.TO_BE_SOLVED.getCode().toString())){
                        repairOrderAdminListPojo.setIfUntreated(RepairOrderDealStatusEnum.UNTREATED.getCode());
                    }else{
                        repairOrderAdminListPojo.setIfUntreated(RepairOrderDealStatusEnum.HAVE_TO_DEAL_WITH.getCode());
                    }
                    repairOrderAdminListPojo.setStatus(RepairOrderStatusEnum.getDesc(Integer.valueOf(status)));
                }
            }
        }

        result.setData(list);

        // 查询工单数量
        Long count = repairOrderMapper.selectRepairOrderCount();
        result.setCount(count);

        ServiceResult<RepairOrderAdminListRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据工单id获取工单内容
     * @param id 工单id
     * @return 返回工单内容
     */
    @Override
    public ServiceResult<RepairOrderInfoRespPojo> getRepairOrderInfoById(Long id) {
        RepairOrder repairOrder = repairOrderMapper.selectById(id);

        RepairOrderInfoRespPojo repairOrderInfoRespPojo = new RepairOrderInfoRespPojo();
        if(repairOrder != null){
            repairOrderInfoRespPojo.setId(repairOrder.getId());
            repairOrderInfoRespPojo.setPriorityName(RepairOrderPriorityEnum.getDesc(repairOrder.getPriority()));
            if(!Strings.isNullOrEmpty(repairOrder.getDealUsername())){
                repairOrderInfoRespPojo.setHeadUser(repairOrder.getDealUsername());
            }else{
                repairOrderInfoRespPojo.setHeadUser(repairOrder.getHeadUsername());
            }
            repairOrderInfoRespPojo.setDescribe(repairOrder.getDescribe());

            // 查询创建用户记录id
            Long createRecordId = repairOrderRecordMapper.selectCreateRecordId(id);

            // 附件信息
            List<RepairOrderFileRespPojo> fileList = repairOrderFileMapper.selectFilesByRepairOrderRecordId(id, createRecordId);
            repairOrderInfoRespPojo.setFileList(fileList);

            // 记录信息
            List<RepairOrderRecordRespPojo> recordList = new ArrayList<>();

            List<RepairOrderRecord> records = repairOrderRecordMapper.selectRecordsList(id);
            if(records != null && records.size() > 0){
                for(RepairOrderRecord repairOrderRecord : records){
                    RepairOrderRecordRespPojo repairOrderRecordRespPojo = new RepairOrderRecordRespPojo();
                    BeanUtils.copyProperties(repairOrderRecord, repairOrderRecordRespPojo);
                    if(!createRecordId.equals(repairOrderRecord.getId())){
                        List<RepairOrderFileRespPojo> files = repairOrderFileMapper.selectFilesByRepairOrderRecordId(id, repairOrderRecord.getId());
                        repairOrderRecordRespPojo.setFileList(files);
                    }
                    if(repairOrderRecordRespPojo.getDescribe() == null){
                        repairOrderRecordRespPojo.setDescribe("");
                    }
                    recordList.add(repairOrderRecordRespPojo);
                }
            }

            repairOrderInfoRespPojo.setRecordList(recordList);
        }

        ServiceResult<RepairOrderInfoRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(repairOrderInfoRespPojo);
        return serviceResult;
    }

    /**
     * 处理虎趣回复工单的mq消息
     * @param json mq消息
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> handleHqReplyRepairOrderMqMsg(JSONObject json) {
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.UPDATE_FAIL;

        HqToCyzRepairOrderReplyVo hqToCyzRepairOrderReplyVo = JSONObject.parseObject(json.toString(), HqToCyzRepairOrderReplyVo.class);
        if(hqToCyzRepairOrderReplyVo != null){
            // 根据虎趣工单id获取工单id
            Long repairOrderId = repairOrderMapper.getIdByHqId(hqToCyzRepairOrderReplyVo.getId());
            if(repairOrderId != null){
                // 添加流程记录
                Date date = new Date(System.currentTimeMillis());
                String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
                String record = dateStr + " 由 " + hqToCyzRepairOrderReplyVo.getReplyUser() + " 更新";
                Long repairOrderRecordId = saveRepairOrderRecord(repairOrderId, record, hqToCyzRepairOrderReplyVo.getDescribe(), hqToCyzRepairOrderReplyVo.getReplyUser());
                if(repairOrderRecordId != null){
                    result = Boolean.TRUE;
                    message = ServiceResult.UPDATE_SUCCESS;

                    // 修改工单状态
                    UpdateWrapper<RepairOrder> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq(Constants.ID, repairOrderId);

                    RepairOrder repairOrder = new RepairOrder();
                    repairOrder.setStatus(RepairOrderStatusEnum.HAVE_TO_REPLY.getCode());
                    repairOrder.setUpdateUser(hqToCyzRepairOrderReplyVo.getReplyUser());
                    repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));

                    int i = repairOrderMapper.update(repairOrder, updateWrapper);
                    if(i > 0){
                        log.info("工单状态修改完成");
                    }

                    // 保存回复的附件信息
                    Map<String, String> map = new HashMap<>();
                    map.put(Constants.NAME, hqToCyzRepairOrderReplyVo.getReplyUser());
                    saveRepairOrderFiles(repairOrderRecordId, repairOrderId, hqToCyzRepairOrderReplyVo.getFileUrls(), map);
                }
            }else{
                log.info("根据虎趣工单id:[{}]未查询到工单id,MQ消息处理失败", hqToCyzRepairOrderReplyVo.getId());
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 根据id获取工单信息
     *
     * @param id 工单id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<RepairOrder> selectById(Long id) {
        RepairOrder repairOrder = repairOrderMapper.selectById(id);

        ServiceResult<RepairOrder> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(repairOrder);
        return serviceResult;
    }

    /**
     * 工单回复
     * @param repairOrderReplyVo 工单回复的vo类
     * @param userInfo 登录用户信息
     * @return 返回回复结果
     */
    @Override
    public ServiceResult<Boolean> replyRepairOrder(RepairOrderReplyVo repairOrderReplyVo, Map<String, String> userInfo, String userId) {
        Boolean result = Boolean.FALSE;

        if(userInfo == null){
            UserInfo userInfo1 = serviceHelper.getUserInfo(userId);
            if(userInfo1 != null){
                userInfo.put(Constants.ID, userId);
                userInfo.put(Constants.NAME, userInfo1.getUsername());
            }
        }

        // 添加流程记录
        Date date = new Date(System.currentTimeMillis());
        String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
        String record = dateStr + " 由 " + userInfo.get(Constants.NAME) + " 更新";
        Long repairOrderRecordId = saveRepairOrderRecord(repairOrderReplyVo.getId(), record, repairOrderReplyVo.getDescribe(), userInfo.get(Constants.ID));
        if(repairOrderRecordId != null){
            result = Boolean.TRUE;

            // 修改工单状态
            UpdateWrapper<RepairOrder> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(Constants.ID, repairOrderReplyVo.getId());

            RepairOrder repairOrder = new RepairOrder();
            repairOrder.setStatus(RepairOrderStatusEnum.HAVE_TO_REPLY.getCode());
            repairOrder.setUpdateUser(userInfo.get(Constants.ID));
            repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));

            int i = repairOrderMapper.update(repairOrder, updateWrapper);
            if(i > 0){
                log.info("工单状态修改完成");
            }

            // 保存回复的附件信息
            saveRepairOrderFiles(repairOrderRecordId, repairOrderReplyVo.getId(), repairOrderReplyVo.getFileUrls(), userInfo);
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 工单解决
     * @param repairOrderSolveVo 工单解决的vo类
     * @param userInfo 登录用户信息
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> solveRepairOrder(RepairOrderSolveVo repairOrderSolveVo, Map<String, String> userInfo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        Boolean result = Boolean.FALSE;
        String message = null;

        // 修改工单状态
        RepairOrder repairOrder = new RepairOrder();
        repairOrder.setStatus(repairOrderSolveVo.getSolvePlan());
        repairOrder.setUpdateUser(userInfo.get(Constants.ID));
        repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));

        UpdateWrapper<RepairOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.ID, repairOrderSolveVo.getId());
        int i = repairOrderMapper.update(repairOrder, updateWrapper);
        if(i > 0){
            result = Boolean.TRUE;
            message = ServiceResult.UPDATE_SUCCESS;

            // 添加流程记录
            Date date = new Date(System.currentTimeMillis());
            String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
            String record = dateStr + " 由 " + userInfo.get(Constants.NAME) + " 解决，解决方案为 " + RepairOrderSolveEnum.getDesc(repairOrderSolveVo.getSolvePlan());
            Long repairOrderRecordId = saveRepairOrderRecord(repairOrderSolveVo.getId(), record, repairOrderSolveVo.getSummary(), userInfo.get(Constants.ID));
            if(repairOrderRecordId != null && (repairOrderSolveVo.getFileUrls() != null && repairOrderSolveVo.getFileUrls().size() > 0)){
                // 保存回复的附件信息
                saveRepairOrderFiles(repairOrderRecordId, repairOrderSolveVo.getId(), repairOrderSolveVo.getFileUrls(), userInfo);
            }
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 工单指派
     * @param orderId 工单id
     * @param headId  FAE的id
     * @param userInfo  登录用户信息
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> assign(Long orderId, Long headId, Map<String, String> userInfo) {
        Boolean result = Boolean.FALSE;
        String message = null;

        // 根据FAE的id获取姓名
        RepairOrderTypeHead repairOrderTypeHead = repairOrderTypeHeadMapper.selectById(headId);

        RepairOrder repairOrder = new RepairOrder();
        repairOrder.setDealUser(headId.toString());
        if(repairOrderTypeHead != null){
            repairOrder.setDealUsername(repairOrderTypeHead.getRealName());
        }
        repairOrder.setUpdateUser(userInfo.get(Constants.ID));
        repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));

        UpdateWrapper<RepairOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.ID, orderId);

        int update = repairOrderMapper.update(repairOrder, updateWrapper);
        if(update > 0){
            result = Boolean.TRUE;
            message = ServiceResult.UPDATE_SUCCESS;

            // 添加流程记录
            Date date = new Date(System.currentTimeMillis());
            String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
            String record = dateStr + " 由 " + userInfo.get(Constants.NAME) + " 指派给 " + repairOrder.getDealUsername();
            saveRepairOrderRecord(orderId, record, null, userInfo.get(Constants.ID));
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 处理虎趣添加工单的mq消息
     * @param json mq消息
     * @return 返回结果
     */
    @Override
    public ServiceResult<Boolean> handleHqAddRepairOrderMqMsg(JSONObject json) {
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.INSERT_FAIL;

        HqToCyzRepairOrderAddVo hqToCyzRepairOrderAddVo = JSONObject.parseObject(json.toString(), HqToCyzRepairOrderAddVo.class);
        if(hqToCyzRepairOrderAddVo != null){
            // 保存工单信息
            RepairOrder repairOrder = new RepairOrder();
            repairOrder.setHqId(hqToCyzRepairOrderAddVo.getId());
            repairOrder.setTopic(hqToCyzRepairOrderAddVo.getTopic());
            repairOrder.setDescribe(hqToCyzRepairOrderAddVo.getDescribe());
            repairOrder.setPriority(hqToCyzRepairOrderAddVo.getPriority());

            Long typeId = hqToCyzRepairOrderAddVo.getTypeId();
            // 获取一级工单类型id
            if(typeId != null){
                RepairOrderType repairOrderType = repairOrderTypeMapper.selectById(typeId);
                if(repairOrderType != null){
                    if(repairOrderType.getClassLevel() == 1){
                        repairOrder.setFirstTypeId(typeId);
                    }else{
                        // 获取一级工单类型id
                        Long firstRepairOrderTypeId = repairOrderTypeMapper.getFirstTypeIdByTypeId(typeId);
                        repairOrder.setFirstTypeId(firstRepairOrderTypeId);
                    }
                }
            }

            repairOrder.setTypeId(typeId);
            // 根据工单类型id查询负责人姓名
            RepairOrderTypeHeadInfoPojo repairOrderTypeHeadInfoPojo = repairOrderTypeHeadMapper.selectRealNameByRepairOrderTypeId(typeId);
            if(repairOrderTypeHeadInfoPojo != null){
                repairOrder.setHeadUser(repairOrderTypeHeadInfoPojo.getUserId().toString());
                repairOrder.setHeadUsername(repairOrderTypeHeadInfoPojo.getUserName());
            }
            repairOrder.setStatus(RepairOrderStatusEnum.TO_BE_SOLVED.getCode());
            repairOrder.setCreateUser(hqToCyzRepairOrderAddVo.getCreateUser());
            repairOrder.setCreateTime(new Date(System.currentTimeMillis()));
            repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));
            repairOrder.setSource(RepairOrderSourceEnum.HQ.getCode());
            repairOrder.setSubmitUsername(hqToCyzRepairOrderAddVo.getCreateUser());
            int insert = repairOrderMapper.insert(repairOrder);
            if(insert > 0){
                result = Boolean.TRUE;
                message = ServiceResult.INSERT_SUCCESS;

                log.info("保存工单信息成功");

                // 保存工单流程记录
                Date date = new Date(System.currentTimeMillis());
                String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
                String record = dateStr + " 由 " + hqToCyzRepairOrderAddVo.getCreateUser() + " 创建";
                Long recordId = saveRepairOrderRecord(repairOrder.getId(), record, null, hqToCyzRepairOrderAddVo.getCreateUser());

                // 保存工单附件信息
                Map<String, String> map = new HashMap<>();
                map.put(Constants.NAME, hqToCyzRepairOrderAddVo.getCreateUser());
                saveRepairOrderFiles(recordId, repairOrder.getId(), hqToCyzRepairOrderAddVo.getFileUrls(), map);
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 新增工单
     * @param repairOrderAddVo 工单新增的vo类
     * @param userId 登录用户id
     * @return 返回新增结果
     */
    @Override
    public ServiceResult<Boolean> addRepairOrder(RepairOrderAddVo repairOrderAddVo, String userId) {
        Boolean result = Boolean.FALSE;

        UserInfo userInfo = serviceHelper.getUserInfo(userId);
        if(userInfo != null){
            // 保存工单信息
            RepairOrder repairOrder = new RepairOrder();
            BeanUtils.copyProperties(repairOrderAddVo, repairOrder);

            // 根据工单类型id查询负责人姓名
            RepairOrderTypeHeadInfoPojo repairOrderTypeHeadInfoPojo = repairOrderTypeHeadMapper.selectRealNameByRepairOrderTypeId(repairOrder.getTypeId());
            if(repairOrderTypeHeadInfoPojo != null){
                repairOrder.setHeadUser(repairOrderTypeHeadInfoPojo.getUserId().toString());
                repairOrder.setHeadUsername(repairOrderTypeHeadInfoPojo.getUserName());
            }

            // 设置一级工单类型id
            repairOrder.setFirstTypeId(selectFirstTypeIdByTypeId(repairOrderAddVo.getTypeId()));
            firstTypeId = null;

            // 目前先设定来源为比一比
            repairOrder.setSource(RepairOrderSourceEnum.B1B.getCode());
            repairOrder.setSubmitUsername(userInfo.getName());

            repairOrder.setStatus(RepairOrderStatusEnum.TO_BE_SOLVED.getCode());
            repairOrder.setCreateUser(userInfo.getId());
            repairOrder.setCreateTime(new Date(System.currentTimeMillis()));
            repairOrder.setUpdateTime(new Date(System.currentTimeMillis()));
            int insert = serviceHelper.getRepairOrderMapper().insert(repairOrder);
            if(insert > 0){
                log.info("保存工单信息成功");

                // 保存工单流程记录
                Date date = new Date(System.currentTimeMillis());
                String dateStr = DateUtils.formatDate(date, DateUtils.DEFAULT_FORMAT);
                String record = dateStr + " 由 " + userInfo.getUsername() + " 创建";
                Long recordId = saveRepairOrderRecord(repairOrder.getId(), record, null, userId);

                // 保存工单附件信息
                Map<String, String> map = new HashMap<>();
                map.put(Constants.ID, userId);
                map.put(Constants.NAME, userInfo.getUsername());
                saveRepairOrderFiles(recordId, repairOrder.getId(), repairOrderAddVo.getFileUrls(), map);

                result = Boolean.TRUE;
            }else{
                log.info("保存工单信息失败");
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 根据工单类型id查询一级工单类型id
     * @param typeId 工单类型id
     * @return 返回一级工单类型id
     */
    private Long selectFirstTypeIdByTypeId(Long typeId) {
        RepairOrderType repairOrderType = repairOrderTypeMapper.selectById(typeId);
        if(repairOrderType.getParentOrderId() != null){
            selectFirstTypeIdByTypeId(repairOrderType.getParentOrderId());
        }else{
            firstTypeId = repairOrderType.getId();
        }
        return firstTypeId;
    }

    /**
     * 保存工单附件信息
     * @param recordId 工单流程id
     * @param repairOrderId 工单id
     * @param fileUrls 附件地址集合
     * @param userInfo 登录用户信息
     */
    private void saveRepairOrderFiles(Long recordId, Long repairOrderId, List<FilesVo> fileUrls, Map<String, String> userInfo) {
        if(recordId != null && fileUrls != null && fileUrls.size() > 0){
            for(FilesVo filesVo : fileUrls){
                RepairOrderFile repairOrderFile = new RepairOrderFile();
                repairOrderFile.setRepairOrderId(repairOrderId);
                repairOrderFile.setRepairOrderRecordsId(recordId);
                repairOrderFile.setFileName(filesVo.getFileName());
                repairOrderFile.setFileSize(filesVo.getFileSize());
                repairOrderFile.setFileType(filesVo.getType());
                repairOrderFile.setFilePath(filesVo.getUrl());
                if(userInfo != null && !userInfo.isEmpty()){
                    repairOrderFile.setCreateUserId(userInfo.get(Constants.ID));
                    repairOrderFile.setCreateUser(userInfo.get(Constants.NAME));
                }
                repairOrderFile.setCreateTime(new Date(System.currentTimeMillis()));
                int insert = serviceHelper.getRepairOrderFileMapper().insert(repairOrderFile);
                if(insert > 0){
                    log.info("保存工单附件信息成功");
                }
            }
        }
    }

    /**
     * 保存工单流程记录信息
     * @param repairOrderId 工单id
     * @param record 流程内容
     * @param describe 描述
     * @param userId 登录用户id
     * @return 返回工单流程记录id
     */
    private Long saveRepairOrderRecord(Long repairOrderId, String record, String describe, String userId){
        RepairOrderRecord repairOrderRecord = new RepairOrderRecord();
        repairOrderRecord.setRepairOrderId(repairOrderId);
        repairOrderRecord.setRecord(record);
        if(!Strings.isNullOrEmpty(describe)){
            repairOrderRecord.setDescribe(describe);
        }
        repairOrderRecord.setCreateUser(userId);
        repairOrderRecord.setCreateTime(new Date(System.currentTimeMillis()));
        int insert = serviceHelper.getRepairOrderRecordMapper().insert(repairOrderRecord);
        if(insert > 0) {
            log.info("保存工单流程记录信息成功");
            return repairOrderRecord.getId();
        }
        return null;
    }
}